﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.StorageHelper;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views
{
    /// <summary>
    /// 漫画书评区
    /// </summary>
    public partial class ComicDiscussionPage : PhoneApplicationPage
    {
        private int comicId = 0, pageIndex = 0, comicUserId = 0;
        private string comicTitle = string.Empty;
        private JsonComicDetailDiscussionInfo currentSelectedItem = null;
        private bool IsLastPage = false;
        // 数据加载的标识
        public bool IsLoading = false;
        // 线程锁的对象
        private object o = new object();

        public ComicDiscussionPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string value;
            base.NavigationContext.QueryString.TryGetValue("comicId", out value);
            int.TryParse(value, out comicId);
            base.NavigationContext.QueryString.TryGetValue("title", out comicTitle);
            this.txtTitle.Text = string.Format("话题：{0}", comicTitle);
            //
            if (comicId <= 0)
            {
                base.NavigationService.GoBack();
                return;
            }
            LoadDiscussData(comicId);
        }

        void LoadDiscussData(int comicId, int pageIndex = 0)
        {
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST,
                string.Format("/comic/getdiscusslist?bigbookid={0}&pageno={1}&pagesize={2}", comicId, pageIndex, KEYS.PAGE_SIZE),
                "&e=", DateTime.Now.Ticks,
                "&", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            //string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            //LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            //cacheHelper.GetDataFromLocalCache(cacheDataKey);
            //if (!cacheHelper.IsReload)
            //{
            //    var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailDiscussion>(cacheHelper.LocalCacheData);
            //    if (!(rootCharacterString != null && rootCharacterString.Info != null))
            //    {
            //        MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
            //    }
            //    else
            //    {
            //        var items = rootCharacterString.Info;
            //        if (items != null && items.Count > 0)
            //        {                        
            //            BindDiscussData(items);
            //        }
            //    }
            //    this.psbStatus.CloseStatusBar();
            //    return;
            //}

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            IsLastPage = true;
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailDiscussion>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null))
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var items = rootCharacterString.Info;
                            if (items != null && items.Count > 0)
                            {
                                //cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                BindDiscussData(items);
                            }
                        }

                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStatus.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void BindDiscussData(ObservableCollection<JsonComicDetailDiscussionInfo> items)
        {
            if (!(items != null && items.Count > 0))
                return;
            this.Dispatcher.BeginInvoke(() =>
            {
                if (pageIndex > 0)
                {
                    if (this.lls.ItemsSource != null && this.lls.ItemsSource.Count > 0)
                    {
                        foreach (var item in items)
                        {
                            this.lls.ItemsSource.Add(item);
                        }
                    }
                    else
                    {
                        this.lls.ItemsSource = items;
                    }
                }
                else
                {
                    this.lls.ItemsSource = items;
                }
            });
        }

        private void lls_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            lock (o)
            {
                if (IsLoading)
                    return;
                if (e.ItemKind != LongListSelectorItemKind.Item)
                    return;
                currentSelectedItem = e.Container.Content as JsonComicDetailDiscussionInfo;
                int selectedIndex = this.lls.ItemsSource.IndexOf(currentSelectedItem);
                int total = this.lls.ItemsSource.Count;
                if (total - selectedIndex <= 2)
                {
                    // 设置IsLoading为true，在加载数据的过程中，禁止多次进入
                    IsLoading = true;
                    if (IsLastPage)
                    {
                        //this.statusBar.OpenStatusBar(AppResources.DataNoMore);
                        //this.statusBar.CloseStatusBar();
                        MessageToastManager.Show(AppResources.DataNoMore);
                        // 修改加载的状态
                        IsLoading = false;
                    }
                    else
                    {
                        this.pageIndex += 1;
                        this.LoadDiscussData(this.comicId, pageIndex);
                        // 修改加载的状态
                        IsLoading = false;
                    }
                }
            }
        }

        private void llsGrid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = ((sender as Grid).DataContext as JsonComicDetailDiscussionInfo);
            if (item == null)
                return;

            this.lls.SelectedItem = item;
            NaviService.Navigate(ComicIslandPage.CommunityDetailPage, string.Concat("?comicId=", item.Id));
        }

        private void llsGrid_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            e.Complete();
            if (e.CumulativeManipulation.Translation.Y > 0)
            {
                //从下往上拉时不处理
                return;
            }

            if (IsLastPage)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    Helper.PageShowDataNoMore<JsonComicDetailDiscussionInfo>(sender, this.lls);
                });
            }
        }



        #region ******************************发布书评话题******************************
        private CustomMessageBox msgBookcase = null;
        private TextBox msgBoxContentTitle = null, msgBoxContentContent = null;
        private string msgBoxContentTitleInfo = string.Empty, msgBoxContentContentInfo = string.Empty;
        private Rating msgBoxRating = null;
        private double msgBoxRatingValue = 4;
        /// <summary>
        ///  发布书评话题
        ///  <para>选择书架上的书</para>
        ///  <para>发布书评话题</para>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarWrite_Click(object sender, EventArgs e)
        {
            ThirdUserLogin();
            if (this.comicUserId <= 0 || this.comicId <= 0)
                return;

            WriteBookDiscuss();
        }

        void WriteBookDiscuss()
        {
            Grid grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition());
            grid.RowDefinitions.Add(new RowDefinition());
            grid.RowDefinitions.Add(new RowDefinition());
            grid.Margin = new Thickness(0, -10, 0, 0);
            msgBoxContentTitle = new TextBox() { MaxLength = 30, Margin = new Thickness(0, -10, 0, 0) };
            if (string.IsNullOrWhiteSpace(msgBoxContentTitleInfo))
                msgBoxContentTitle.Text = AppResources.CommunityInputTitle;
            else
                msgBoxContentTitle.Text = msgBoxContentTitleInfo;
            msgBoxContentContent = new TextBox() { MinHeight = 120, MaxHeight = 120, AcceptsReturn = true, Margin = new Thickness(0, -10, 0, 0) };
            if (string.IsNullOrWhiteSpace(msgBoxContentTitleInfo))
                msgBoxContentContent.Text = AppResources.CommunityInputContent;
            else
                msgBoxContentContent.Text = msgBoxContentContentInfo;
            msgBoxContentContent.TextWrapping = TextWrapping.Wrap;
            msgBoxContentContent.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
            msgBoxContentContent.Style = Application.Current.Resources["TextBoxStyleComic"] as Style;

            this.msgBoxRating = new Rating() { Height = 40, Width = 200, Value = this.msgBoxRatingValue, Margin = new Thickness(0, 5, 0, 10), Background = new SolidColorBrush(Colors.Transparent), HorizontalAlignment = System.Windows.HorizontalAlignment.Center };
            if (this.msgBoxRatingValue != 4)
                this.msgBoxRating.Value = this.msgBoxRatingValue;
            this.msgBoxRating.FilledItemStyle = Application.Current.Resources["ratingDiscussionFilled"] as Style;
            this.msgBoxRating.UnfilledItemStyle = Application.Current.Resources["ratingDiscussionUnFilled"] as Style;
            TiltEffect.SetIsTiltEnabled(msgBoxContentTitle, true);
            TiltEffect.SetIsTiltEnabled(msgBoxContentContent, true);
            msgBoxContentTitle.GotFocus += txtTitle_GotFocus;
            msgBoxContentTitle.LostFocus += txtTitle_LostFocus;
            msgBoxContentContent.LostFocus += txtContent_LostFocus;
            msgBoxContentContent.GotFocus += txtContent_GotFocus;

            Grid.SetRow(this.msgBoxRating, 0);
            Grid.SetRow(msgBoxContentTitle, 1);
            Grid.SetRow(msgBoxContentContent, 2);
            grid.Children.Add(this.msgBoxRating);
            grid.Children.Add(msgBoxContentTitle);
            grid.Children.Add(msgBoxContentContent);
            this.msgBookcase = new CustomMessageBox()
            {
                VerticalAlignment = System.Windows.VerticalAlignment.Bottom,
                Caption = "发布书评话题",
                Content = grid,
                LeftButtonContent = "发布",
                RightButtonContent = "取消"
            };
            this.msgBookcase.Style = Application.Current.Resources["CustomMessageBoxStyleComic"] as Style;
            //
            this.msgBookcase.Dismissed += (s1, e1) =>
            {
                switch (e1.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        string title = msgBoxContentTitle.Text.Trim();
                        string content = msgBoxContentContent.Text.Trim();
                        this.msgBoxRatingValue = this.msgBoxRating.Value;
                        if (string.IsNullOrWhiteSpace(title) || string.IsNullOrWhiteSpace(content) || AppResources.CommunityInputTitle.Equals(title) || AppResources.CommunityInputContent.Equals(content))
                        {
                            MessageToastManager.Show("请输入标题及其内容！");
                            return;
                        }
                        this.msgBoxContentTitleInfo = title;
                        this.msgBoxContentContentInfo = content;
                        if (title.Length < 3)
                        {
                            MessageToastManager.Show("标题不少于3个字！");
                            return;
                        }
                        if (content.Length < 10)
                        {
                            MessageToastManager.Show("内容不少于10个字！");
                            return;
                        }
                        this.AddDiscuss(content, title, this.comicId, this.msgBoxRatingValue);
                        break;
                    case CustomMessageBoxResult.RightButton:
                    case CustomMessageBoxResult.None:
                    default:
                        break;
                }
            };

            this.msgBookcase.Show();
        }

        void AddDiscuss(string content, string title, int discussComicId, double gradeScore)
        {
            if (!(this.comicUserId > 0 && !string.IsNullOrWhiteSpace(title) && !string.IsNullOrWhiteSpace(content) && discussComicId > 0))
            {
                return;
            }

            //{"content":"正常v故宫v广告费的v更多的","userid":"247460","gradescore":3,"title":"不要这样下去","bigbookid":"14603","type":"0","communityid":"2"}
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/adddiscuss", "?", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("content", content);
            parameters.Add("userid", this.comicUserId);
            parameters.Add("title", title);
            parameters.Add("communityid", "2");//书评话题
            parameters.Add("gradescore", gradeScore);//书评区有值
            parameters.Add("bigbookid", discussComicId);//书评区有值
            parameters.Add("type", "0");//0是添加

            PostClientHelper proxy = new PostClientHelper(parameters);
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                    return;
                }

                #region 获取结果处理
                string result = e.Result;

                if (string.IsNullOrWhiteSpace(result))
                {
                    LogHelper.LogError("Result is empty.");
                    //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                    return;
                }
                //
                if (result.StartsWith("exception:"))
                {
                    LogHelper.LogError(result);
                    //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                    return;
                }

                LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                //
                var rootCharacterString = JSONHelper.Deserialize<JsonAddFeedBack>(result);
                if (KEYS.JSON_SUCCESS == rootCharacterString.Code)
                {
                    MessageToastManager.Show("操作成功！");
                    this.msgBoxContentTitleInfo = string.Empty;
                    this.msgBoxContentContentInfo = string.Empty;
                    this.msgBoxRatingValue = 4;
                    this.pageIndex = 0;//重新加载
                    this.LoadDiscussData(this.comicId);
                }
                else
                {
                    MessageToastManager.Show("操作失败！");
                    LogHelper.LogError("操作失败:\t" + rootCharacterString.CodeMsg);
                }

                #endregion 获取结果处理
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }

        #region ********************获取当前登录用户********************
        void ThirdUserLogin()
        {
            if (!IsolatedStorageHelper.Instance.FileExists(KEYS.KEY_UserThirdLoginInfo))
            {
                ConfirmThirdUserLogin();
                return;

            }
            string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.KEY_UserThirdLoginInfo);
            if (string.IsNullOrWhiteSpace(localCacheData))
            {
                ConfirmThirdUserLogin();
                return;
            }
            var userInfo = JSONHelper.Deserialize<UserThirdLoginInfo>(localCacheData);
            if (userInfo == null)
            {
                ConfirmThirdUserLogin();
                return;
            }
            if (userInfo.ComicUserId <= 0)
            {
                ConfirmThirdUserLogin();
                return;
            }
            this.comicUserId = userInfo.ComicUserId;
        }

        void ConfirmThirdUserLogin()
        {
            this.oauthControl.OnClose += delegate(object sender, EventArgs e)
            {
                this.popupLogin.IsOpen = false;
            };
            this.popupLogin.IsOpen = true;
        }
        #endregion ********************获取当前登录用户********************

        #region ********************LostFocus/GotFocus********************
        void txtContent_LostFocus(object sender, RoutedEventArgs e)
        {
            if (this.msgBookcase != null)
            {
                this.msgBookcase.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                var txtControl = sender as TextBox;
                if (txtControl == null)
                    return;
                if (string.IsNullOrWhiteSpace(txtControl.Text.Trim()))
                {
                    txtControl.Text = AppResources.CommunityInputContent;
                }
            }
        }

        void txtContent_GotFocus(object sender, RoutedEventArgs e)
        {
            if (this.msgBookcase != null)
            {
                this.msgBookcase.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                var txtControl = sender as TextBox;
                if (txtControl == null)
                    return;
                if (AppResources.CommunityInputContent.Equals((sender as TextBox).Text))
                {
                    txtControl.Text = string.Empty;
                }
            }
        }

        void txtTitle_LostFocus(object sender, RoutedEventArgs e)
        {
            if (this.msgBookcase != null)
            {
                this.msgBookcase.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                var txtControl = sender as TextBox;
                if (txtControl == null)
                    return;
                if (string.IsNullOrWhiteSpace(txtControl.Text.Trim()))
                {
                    txtControl.Text = AppResources.CommunityInputTitle;
                }

            }
        }

        void txtTitle_GotFocus(object sender, RoutedEventArgs e)
        {
            if (this.msgBookcase != null)
            {
                this.msgBookcase.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                var txtControl = sender as TextBox;
                if (txtControl == null)
                    return;
                if (AppResources.CommunityInputTitle.Equals((sender as TextBox).Text))
                {
                    txtControl.Text = string.Empty;
                }
            }
        }
        #endregion ********************LostFocus/GotFocus********************

        #endregion ******************************发布书评话题******************************




    }
}